<template>
    <Menu ref="menuRef" class="dynamic-menu" mode="inline" :openKeys="collapsed ? getOpenMenuKeys : []"
        :selectedKeys="[getActiveTab?.viewId]" :inline-collapsed="!collapsed" @select="onMenuItemSelect">
        <template v-for="view in getViewTree">
            <!--menu-->
            <template v-if="view.children.length <= 0">
                <MenuItem :key="view?.id" v-if="!view.hidden">
                <template #icon>
                    <component v-if="view.icon" :is="view.icon" />
                </template>
                <span>{{ view.title }}</span>
                </MenuItem>
            </template>
            <!--subMenu-->
            <template v-else>
                <DynamicMenuItem :view="view" />
            </template>
        </template>
    </Menu>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue';
import DynamicMenuItem from './item.vue';
import { useTab, useAttribute } from 'vue3-vanilla-tab';
import { Menu, MenuItem } from 'vue3-vanilla-tab';
import { toRefs } from 'vue';

const {
    getOpenMenuKeys,
    getActiveTab,
    getViewTree,
    getViewList,
} = useAttribute();
const { openTab } = useTab();

const props = withDefaults(defineProps<{
    collapsed?: boolean;
}>(), {
    collapsed: true
});
const { collapsed } = toRefs(props);

const onMenuItemSelect = ({ key }) => {
    try {
        const findView = getViewList.value.find(item => item.id == key);
        if (findView) {
            const { id, props, title } = findView;
            openTab(id, props as any, { title });
        }
    } catch (error) {
        message.error(error.message);
    }
}

</script>

<style lang="less" scoped>
.dynamic-menu {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
    width: 100% !important;
    border: 0 !important;
}
</style>